<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.type" placeholder="类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
        v-permission="['announcement:create']"
      >
        新增
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-s-data"
        @click="handleStats"
        v-permission="['announcement:stats']"
      >
        统计
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="标题" min-width="150px">
        <template slot-scope="{row}">
          <router-link :to="'/announcement/detail/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
          <el-tag v-if="row.isTop === 1" type="danger" size="mini" style="margin-left: 5px">置顶</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type | typeFilter">{{ row.type | typeNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布人" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.publisherName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布部门" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.departmentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.publishTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.readCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status | statusNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" v-permission="['announcement:update']">
            编辑
          </el-button>
          <el-button v-if="row.status === 0" size="mini" type="success" @click="handlePublish(row)" v-permission="['announcement:publish']">
            发布
          </el-button>
          <el-button v-if="row.status === 1" size="mini" type="warning" @click="handleCancel(row)" v-permission="['announcement:cancel']">
            撤销
          </el-button>
          <el-button v-if="row.isTop === 0" size="mini" type="info" @click="handleTop(row, true)" v-permission="['announcement:top']">
            置顶
          </el-button>
          <el-button v-else size="mini" type="info" @click="handleTop(row, false)" v-permission="['announcement:top']">
            取消置顶
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)" v-permission="['announcement:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 编辑弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 90%; margin-left:50px;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择类型">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <tinymce v-model="temp.content" :height="300" />
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker
            v-model="temp.startTime"
            type="datetime"
            placeholder="选择生效时间"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="失效时间" prop="endTime">
          <el-date-picker
            v-model="temp.endTime"
            type="datetime"
            placeholder="选择失效时间"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="发布范围" prop="scopes">
          <el-tabs v-model="scopeActiveTab">
            <el-tab-pane label="全员" name="all">
              <el-checkbox v-model="scopeAll">全体员工</el-checkbox>
            </el-tab-pane>
            <el-tab-pane label="部门" name="department">
              <el-select
                v-model="scopeDepartments"
                multiple
                filterable
                placeholder="请选择部门"
                style="width: 100%"
              >
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-tab-pane>
            <el-tab-pane label="角色" name="role">
              <el-select
                v-model="scopeRoles"
                multiple
                filterable
                placeholder="请选择角色"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-tab-pane>
            <el-tab-pane label="个人" name="user">
              <el-select
                v-model="scopeUsers"
                multiple
                filterable
                placeholder="请选择用户"
                style="width: 100%"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            multiple
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/doc/docx/xls/xlsx/pdf文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
      </div>
    </el-dialog>

    <!-- 统计弹窗 -->
    <el-dialog title="公告统计" :visible.sync="statsDialogVisible" width="800px">
      <div class="stats-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-container">
              <h3>公告类型分布</h3>
              <div id="typeChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-container">
              <h3>部门发布统计</h3>
              <div id="departmentChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <div class="chart-container">
              <h3>公告发布趋势</h3>
              <div id="trendChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAnnouncementPage, createAnnouncement, updateAnnouncement, deleteAnnouncement, publishAnnouncement, cancelAnnouncement, topAnnouncement, getAnnouncementStats } from '@/api/announcement'
import { getAttachmentList, uploadAttachment, deleteAttachment } from '@/api/announcement/attachment'
import { getDepartmentList } from '@/api/system/department'
import { getRoleList } from '@/api/system/role'
import { getUserList } from '@/api/system/user'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'
import permission from '@/directive/permission/index.js'
import { getToken } from '@/utils/auth'
import * as echarts from 'echarts'

export default {
  name: 'AnnouncementList',
  components: { Pagination, Tinymce },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: 'success',
        2: 'primary',
        3: 'warning'
      }
      return typeMap[type]
    },
    typeNameFilter(type) {
      const typeMap = {
        1: '通知',
        2: '通告',
        3: '提醒'
      }
      return typeMap[type]
    },
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = {
        0: '草稿',
        1: '已发布',
        2: '已过期',
        3: '已撤销'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        title: undefined,
        type: undefined,
        status: undefined
      },
      typeOptions: [
        { label: '通知', value: 1 },
        { label: '通告', value: 2 },
        { label: '提醒', value: 3 }
      ],
      statusOptions: [
        { label: '草稿', value: 0 },
        { label: '已发布', value: 1 },
        { label: '已过期', value: 2 },
        { label: '已撤销', value: 3 }
      ],
      temp: {
        id: undefined,
        title: '',
        content: '',
        type: 1,
        startTime: '',
        endTime: '',
        status: 0,
        scopes: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑公告',
        create: '新增公告'
      },
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
        startTime: [{ required: true, message: '生效时间不能为空', trigger: 'change' }],
        endTime: [{ required: true, message: '失效时间不能为空', trigger: 'change' }]
      },
      // 发布范围相关
      scopeActiveTab: 'all',
      scopeAll: false,
      scopeDepartments: [],
      scopeRoles: [],
      scopeUsers: [],
      departmentOptions: [],
      roleOptions: [],
      userOptions: [],
      // 附件相关
      uploadUrl: process.env.VUE_APP_BASE_API + '/announcement-attachments/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadData: {
        announcementId: 0
      },
      fileList: [],
      // 统计相关
      statsDialogVisible: false,
      typeChart: null,
      departmentChart: null,
      trendChart: null
    }
  },
  created() {
    this.getList()
    this.getDepartments()
    this.getRoles()
    this.getUsers()
  },
  methods: {
    getList() {
      this.listLoading = true
      getAnnouncementPage(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        content: '',
        type: 1,
        startTime: '',
        endTime: '',
        status: 0,
        scopes: []
      }
      this.scopeAll = false
      this.scopeDepartments = []
      this.scopeRoles = []
      this.scopeUsers = []
      this.fileList = []
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.buildScopes()
          createAnnouncement(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      
      // 获取附件列表
      getAttachmentList(row.id).then(response => {
        this.fileList = response.data.map(item => {
          return {
            name: item.name,
            url: item.path,
            id: item.id
          }
        })
      })
      
      // 设置上传参数
      this.uploadData.announcementId = row.id
      
      // 解析发布范围
      if (row.scopes && row.scopes.length > 0) {
        row.scopes.forEach(scope => {
          if (scope.scopeType === 1) {
            this.scopeAll = true
          } else if (scope.scopeType === 2) {
            this.scopeDepartments.push(scope.scopeId)
          } else if (scope.scopeType === 3) {
            this.scopeRoles.push(scope.scopeId)
          } else if (scope.scopeType === 4) {
            this.scopeUsers.push(scope.scopeId)
          }
        })
      }
      
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.buildScopes()
          updateAnnouncement(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAnnouncement(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handlePublish(row) {
      this.$confirm('确认发布该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        publishAnnouncement(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '发布成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleCancel(row) {
      this.$confirm('确认撤销该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelAnnouncement(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '撤销成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleTop(row, isTop) {
      topAnnouncement(row.id, isTop).then(() => {
        this.$notify({
          title: '成功',
          message: isTop ? '置顶成功' : '取消置顶成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    // 构建发布范围
    buildScopes() {
      const scopes = []
      if (this.scopeAll) {
        scopes.push({
          scopeType: 1,
          scopeId: null,
          scopeName: '全体员工'
        })
      }
      
      if (this.scopeDepartments.length > 0) {
        this.scopeDepartments.forEach(deptId => {
          const dept = this.departmentOptions.find(item => item.id === deptId)
          scopes.push({
            scopeType: 2,
            scopeId: deptId,
            scopeName: dept ? dept.name : ''
          })
        })
      }
      
      if (this.scopeRoles.length > 0) {
        this.scopeRoles.forEach(roleId => {
          const role = this.roleOptions.find(item => item.id === roleId)
          scopes.push({
            scopeType: 3,
            scopeId: roleId,
            scopeName: role ? role.name : ''
          })
        })
      }
      
      if (this.scopeUsers.length > 0) {
        this.scopeUsers.forEach(userId => {
          const user = this.userOptions.find(item => item.id === userId)
          scopes.push({
            scopeType: 4,
            scopeId: userId,
            scopeName: user ? user.name : ''
          })
        })
      }
      
      this.temp.scopes = scopes
    },
    // 获取部门列表
    getDepartments() {
      getDepartmentList().then(response => {
        this.departmentOptions = response.data
      })
    },
    // 获取角色列表
    getRoles() {
      getRoleList().then(response => {
        this.roleOptions = response.data
      })
    },
    // 获取用户列表
    getUsers() {
      getUserList().then(response => {
        this.userOptions = response.data
      })
    },
    // 附件上传成功
    handleUploadSuccess(response, file, fileList) {
      this.$notify({
        title: '成功',
        message: '附件上传成功',
        type: 'success',
        duration: 2000
      })
      this.fileList = fileList
    },
    // 移除附件
    handleRemove(file) {
      if (file.id) {
        deleteAttachment(file.id).then(() => {
          this.$notify({
            title: '成功',
            message: '附件删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    // 统计
    handleStats() {
      this.statsDialogVisible = true
      this.$nextTick(() => {
        this.initCharts()
      })
    },
    initCharts() {
      getAnnouncementStats().then(response => {
        const data = response.data
        
        // 初始化类型分布图表
        this.typeChart = echarts.init(document.getElementById('typeChart'))
        const typeOption = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 10,
            data: ['通知', '通告', '提醒']
          },
          series: [
            {
              name: '公告类型',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: data.typeStats[0].count, name: '通知' },
                { value: data.typeStats[1].count, name: '通告' },
                { value: data.typeStats[2].count, name: '提醒' }
              ]
            }
          ]
        }
        this.typeChart.setOption(typeOption)
        
        // 初始化部门发布统计图表
        this.departmentChart = echarts.init(document.getElementById('departmentChart'))
        const departmentNames = data.departmentStats.map(item => item.departmentName)
        const departmentValues = data.departmentStats.map(item => item.count)
        const departmentOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: departmentNames,
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: departmentValues,
              type: 'bar'
            }
          ]
        }
        this.departmentChart.setOption(departmentOption)
        
        // 初始化发布趋势图表
        this.trendChart = echarts.init(document.getElementById('trendChart'))
        const dates = data.trendStats.map(item => item.date)
        const counts = data.trendStats.map(item => item.count)
        const trendOption = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: counts,
              type: 'line',
              smooth: true
            }
          ]
        }
        this.trendChart.setOption(trendOption)
      })
    }
  }
}
</script>

<style scoped>
.link-type {
  color: #337ab7;
}
.chart-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.chart-container h3 {
  margin-top: 0;
  margin-bottom: 15px;
  text-align: center;
}
</style> 